/**
 * 调试工具
 * 用于诊断token和认证问题
 */

import { useUserStore } from '@/stores/user'
import Cookies from 'js-cookie'

// 调试token状态
export function debugTokenStatus() {
  const userStore = useUserStore()
  
  console.log('=== Token 调试信息 ===')
  console.log('Store Token:', userStore.token)
  console.log('Cookie Token:', Cookies.get('token'))
  console.log('用户信息:', userStore.user)
  console.log('权限列表:', userStore.permissions)
  console.log('是否已登录:', userStore.isLoggedIn)
  console.log('========================')
}

// 调试请求头
export function debugRequestHeaders() {
  const userStore = useUserStore()
  const token = userStore.token || Cookies.get('token')
  
  console.log('=== 请求头调试信息 ===')
  console.log('当前Token:', token)
  console.log('Authorization Header:', token ? `Bearer ${token}` : '无')
  console.log('========================')
}

// 调试API响应
export function debugApiResponse(response: any, endpoint: string) {
  console.log(`=== API响应调试 (${endpoint}) ===`)
  console.log('响应状态:', response.status)
  console.log('响应数据:', response.data)
  console.log('响应头:', response.headers)
  console.log('========================')
}

// 调试登录流程
export function debugLoginFlow(loginData: any, response: any) {
  console.log('=== 登录流程调试 ===')
  console.log('登录数据:', loginData)
  console.log('登录响应:', response)
  
  const userStore = useUserStore()
  console.log('登录后Token:', userStore.token)
  console.log('登录后用户:', userStore.user)
  console.log('登录后权限:', userStore.permissions)
  console.log('========================')
}

// 检查token有效性
export function checkTokenValidity() {
  const userStore = useUserStore()
  const cookieToken = Cookies.get('token')
  
  const issues = []
  
  if (!userStore.token && !cookieToken) {
    issues.push('Token完全缺失')
  }
  
  if (userStore.token !== cookieToken) {
    issues.push('Store和Cookie中的Token不一致')
  }
  
  if (userStore.token && !userStore.user) {
    issues.push('有Token但没有用户信息')
  }
  
  if (userStore.user && !userStore.permissions.length) {
    issues.push('有用户信息但没有权限')
  }
  
  if (issues.length > 0) {
    console.warn('=== Token有效性检查发现问题 ===')
    issues.forEach(issue => console.warn('-', issue))
    console.warn('========================')
    return false
  }
  
  console.log('Token有效性检查通过')
  return true
}

// 重置认证状态
export function resetAuthState() {
  const userStore = useUserStore()
  
  console.log('=== 重置认证状态 ===')
  console.log('重置前Token:', userStore.token)
  console.log('重置前用户:', userStore.user)
  
  userStore.token = ''
  userStore.user = null
  userStore.permissions = []
  Cookies.remove('token')
  
  console.log('重置后Token:', userStore.token)
  console.log('重置后用户:', userStore.user)
  console.log('========================')
}

// 导出调试工具
export default {
  debugTokenStatus,
  debugRequestHeaders,
  debugApiResponse,
  debugLoginFlow,
  checkTokenValidity,
  resetAuthState
} 